<?php

namespace app\model\v1\recruit;

use app\model\message\service\StoreService;
use app\model\user\User;
use app\model\v1\recovery\RecoveryQuestionCate;
use app\model\v1\recovery\RecoveryReport;
use crmeb\traits\ModelTrait;
use think\Exception;
use think\facade\Db;
use think\Model;

class RecruitCompany extends Model
{

    use ModelTrait;

    protected $updateTime = false;
    protected $createTime = false;

    protected $hidden = [
    //    'create_time','update_time','delete_time'
    ];

	public function companytype ()
	{
			return $this->hasOne ('recruit_firm_type','id','company_type');
	}

    public function kefu()
    {
        return $this->hasOne (User::class,'uid','kefu_id');
    }



    /**
     * 求职招聘后台 - 企业认证管理列表
     * @param $param
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getRecruitCompanyList($param = [])
    {
        $data["data"] = self::field("id,name,introduction,industry_id,contact_name,contact_email,contact_phone,business_license_name,company_type,business_license_images,
            corporate_capacity_images,website,logo_image,address,company_nums,status,audit_state,created_at,audit_at,refuse_reason,kefu_id,chat_count_config,phone_count_config,
            chat_count_config_inte,phone_count_config_inte,
            case when status=1 then '启用'
            when status =2 then '禁用'
            end as status_text
            ")
            ->with([
                'kefu' => function($query) {
                    $query->field ('uid,nickname,real_name,phone');
                }
            ])
            ->whereNULL("delete_at")
            ->where(function ($query) use ($param){
                if(!empty($param["name"])) $query->where("name", 'like', '%'.$param["name"].'%');   //根据企业名称搜索
                if(!empty($param['time'])){    //根据创建日期搜索
                    $wheretime = explode(',',$param['time']);
                    $query->where('created_at', 'between', [$wheretime[0],$wheretime[1]]);
                }
            })
            ->order("id", "desc")
            ->page($param["page"], $param["limit"])
            ->select()
            ->toArray();

        $data["count"] = self::whereNULL("delete_at")
            ->where(function ($query) use ($param){
                if(!empty($param["name"])) $query->where("name", 'like', '%'.$param["name"].'%');   //根据企业名称搜索
                if(!empty($param['time'])){    //根据创建日期搜索
                    $wheretime = explode(',',$param['time']);
                    $query->where('created_at', 'between', [$wheretime[0],$wheretime[1]]);
                }
            })
            ->count();

        if(!empty($data['data'] )) {
            foreach ($data['data'] as $key => &$val) {
                $img = explode(",", $val["corporate_capacity_images"]);
                $val["positive_img"] = $img[0];
                $val["side_img"] = $img[0];
            }
        }


        return $data;

    }



    public static function getRecruitCompanyDetail($param = [])
    {
        $detail = self::field("*,
            case when status=1 then '启用'
            when status =2 then '禁用'
            end as status_text
            ")
            ->where("id", $param["id"])
            ->find();

        if(!empty($detail)) {
            $img = explode(",", $detail["corporate_capacity_images"]);
            $detail["positive_img"] = $img[0];
            $detail["side_img"] = $img[0];
            if($detail["audit_state"] == 1){
                $detail["audit_state_text"] = "待审核";
            }elseif($detail["audit_state"] == 2){
                $detail["audit_state_text"] = "审核通过";
            }elseif($detail["audit_state"] == 3){
                $detail["audit_state_text"] = "审核不通过";
            }
        }
        return $detail;
    }


    /**
     * 求职招聘后台 - 企业认证管理列表 - 审核按钮
     * @param $param
     * @return RecruitCompany
     */
    public static function enableCompanyState($param = [])
    {
        $update = ['audit_state' => $param["audit_state"]];
        if(!empty($param["refuse_reason"])) $update["refuse_reason"] = $param["refuse_reason"];

        $res = self::where("id", $param['id'])->update($update);
        return $res;
    }


    /**
     * 求职招聘后台 - 举报管理列表
     * @param $param
     * @return mixed
     */
    public static function getReportList($param = [])
    {
        $order = ["a.id"=>"desc"];

        $data["data"] = RecoveryReport::alias("a")
            ->field ("a.*,b.cate_name,c.nickname,c.phone")
            ->join ('recovery_question_cate b','a.cate=b.id','left')
            ->join ('user c','a.uid=c.uid','left')
            ->where(function ($query) use ($param){
                $query->whereNull("a.delete_time");
                if(!empty($param['time'])){    //根据创建日期搜索
                    $wheretime = explode (',',$param['time']);
                    $query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                //根据用户昵称/联系方式搜索
                if(!empty($param["word"])) $query->where("c.nickname",'like', '%'.$param["word"].'%')->whereOr("c.phone",'like', '%'.$param["word"].'%');
            })
            ->order($order)
            ->page($param['page'], $param['limit'])
            ->select()->toArray();

        $data["count"] = RecoveryReport::alias("a")
            ->field ("a.*,b.cate_name,c.nickname,c.phone")
            ->join ('recovery_question_cate b','a.cate=b.id','left')
            ->join ('user c','a.uid=c.uid','left')
            ->where(function ($query) use ($param){
                $query->whereNull("a.delete_time");
                if(!empty($param['time'])){    //根据创建日期搜索
                    $wheretime = explode (',',$param['time']);
                    $query->where('a.create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                //根据用户昵称/联系方式搜索
                if(!empty($param["word"])) $query->where("c.nickname",'like', '%'.$param["word"].'%')->whereOr("c.phone",'like', '%'.$param["word"].'%');
            })
            ->count();

        return $data;
    }


    /**
     * 求职招聘后台 - 举报管理列表 - 查看
     * @param $param
     * @return mixed
     */
    public static function getRecruitReportDetail($param = [])
    {
        $data = RecoveryReport::alias("a")
            ->field ("a.*,b.cate_name,c.nickname,c.phone")
            ->join ('recovery_question_cate b','a.cate=b.id','left')
            ->join ('user c','a.uid=c.uid','left')
            ->where(function ($query) use ($param){
                $query->whereNull("a.delete_time");
                $query->where("a.id", $param["id"]);
            })
            ->find();

        return $data;
    }


    /**
     * 求职招聘后台 - 类型配置管理列表
     * @param $param
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public static function getQuestionCateList($param = [])
    {
        $order = ["id"=>"desc"];

        $data["data"] = RecoveryQuestionCate::whereNull("delete_time")
            ->field("*, 
            case when status=1 then '启用' 
            when status=2 then '禁用' 
            end as status_text ")
            ->where(function ($query) use ($param){
                $query->whereNull('delete_time');
                $query->where("type", '>', 30);
                if(!empty($param['time'])){    //根据创建日期搜索
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("cate_name",'like', '%'.$param["word"].'%');
                if(!empty($param["cate_id"])) $query->where("type", $param["cate_id"]);
            })
            ->order($order)
            ->page($param['page'], $param['limit'])
            ->select()->toArray();

        $data["count"] = RecoveryQuestionCate::whereNull("delete_time")
            ->field("*")
            ->where(function ($query) use ($param){
                $query->whereNull('delete_time');
                $query->where("type", '>', 30);
                if(!empty($param['time'])){
                    $wheretime = explode (',',$param['time']);
                    $query->where('create_time', 'between', [strtotime($wheretime[0]),strtotime($wheretime[1])]);
                }
                if(!empty($param["word"])) $query->where("cate_name",'like', '%'.$param["word"].'%');
                if(!empty($param["cate_id"])) $query->where("type", $param["cate_id"]);
            })
            ->count();

        return $data;
    }



    /**
     * 类型配置管理列表 - 添加
     * @param $param
     * @return int|string
     */
    public static function addQuestionCate($param = [])
    {
        $add = [
            "uid"           => $param["admin_id"],  //创建人id
            "cate_name"     => $param["cate_name"] ?? '', //属性名称
            "type"          => $param["type"],  //类型
            "create_time"   => time(),
        ];
        return RecoveryQuestionCate::insert($add);
    }


    /**
     * 类型配置管理列表 - 编辑
     * @param $param
     * @return RecruitCompany
     */
    public static function updateQuestionCate($param = [])
    {
        $update["update_time"] = time();  //更新时间
        if(!empty($param["cate_name"]))     $update["cate_name"] = $param["cate_name"];  //分类名称
        if(!empty($param["type"]))          $update["type"] = $param["type"]; //类型

        return RecoveryQuestionCate::where("id", $param["id"])->update($update);
    }


    public static function getCompanyKefuId($company_id = '', $uid = '')
    {
        if(empty($company_id) && empty($uid)) return '';

        if(!empty($company_id)){
            $company_kefu_id =  self::where("id", $company_id)->value('kefu_id') ?? '';
            if(!empty($company_kefu_id)){
                return $company_kefu_id;
            }else{
                if(!empty($uid)){
                    $kefu_id = StoreService::where("uid", $uid)->value('id') ?? '';
                    return $kefu_id;
                }
            }
        }

        if(!empty($uid)){
            $kefu_id = StoreService::where("uid", $uid)->value('id') ?? '';
            return $kefu_id;
        }
    }




    public static function getCustomerUserList($params = [])
    {
        $data = User::whereNULL("delete_time")->where("status", 1)->field("uid,nickname,phone,real_name")->select()->toArray();
        if(!empty($data)){
            foreach ($data as $key => &$val){
                $val["customer"] = $val["phone"].'|'.$val['real_name'];
            }
        }
        return $data;
    }


    public static function setCompanyCustomer($param = [])
    {
        try {
            Db::startTrans();

            $update["kefu_id"] = $param["kefu_id"];
            self::where("id", $param["id"])->update($update);

            $userinfo = User::where("uid", $param["kefu_id"])->find();
            if(!empty($userinfo)) $userinfo = $userinfo->toArray();

            $find = StoreService::where("account", $userinfo["phone"])->whereOr("phone", $userinfo["phone"])->find();
            if(empty($find)){
                $add_service = [
                    "uid"       => $param["kefu_id"],
                    "mer_id"    => $param["id"],
                    "account"   => $userinfo["phone"] ?? '',
                    "password"  => password_hash('123456', PASSWORD_DEFAULT),
                    "avatar"    => $userinfo["avatar"] ?? '',
                    "nickname"  => $userinfo["nickname"] ?? '',
                    "phone"     => $userinfo["phone"] ?? '',
                    "notify"    => 1,
                    "customer"  => 1,
                    "type"      => 2,
                    "add_time"  => time(),
                ];
                StoreService::insert($add_service);
            }

            Db::commit();
            return true;
        }catch (\Throwable $e){
            Db::rollback();
            Throw new Exception($e->getMessage());
            return false;
        }
    }


    /**
     * 主聊打管理列表 - 编辑
     * @param $param
     * @return RecruitCompany
     */
    public static function updateChatPhone($param = [])
    {
        $update["updated_at"] = date("Y-m-d H:i:s");  //更新时间
        if(!empty($param["chat_count_config"]))         $update["chat_count_config"] = $param["chat_count_config"];
        if(!empty($param["phone_count_config"]))        $update["phone_count_config"] = $param["phone_count_config"];
        if(!empty($param["chat_count_config_inte"]))    $update["chat_count_config_inte"] = $param["chat_count_config_inte"];
        if(!empty($param["phone_count_config_inte"]))   $update["phone_count_config_inte"] = $param["phone_count_config_inte"];

        return self::where("id", $param["id"])->update($update);
    }




    public static function getRecruitCompanyData($id = 0)
    {
        return self::whereNull("delete_at")->where("status", 1)->where("audit_state", 1)->select();
    }




}